import React, { useState, useEffect, useRef } from 'react'
import { Modal, Form, Upload, Button, message } from 'antd'
import { awaitWrap, getUploadPropsFn } from '@js/tool'
import { UploadOutlined } from '@ant-design/icons'
import style from './Index.module.less'
import { updateRequest } from './ajax'
import { submitFiles } from '@js/request'

const { Item } = Form

async function updateHandle (id, d, refreshFn, hide) {
  if (d.file.fileList.length === 0) {
    return false
  }
  const h = message.loading('提交中', 120)
  const fileids = await submitFiles(d.file.fileList)
  const [e] = await awaitWrap(updateRequest(id, fileids))
  h()
  if (e === null) {
    message.success('更新成功')
    refreshFn()
    hide()
  }
}

function submitHandle (id, d, refreshFn, hide) {
  updateHandle(id, d, refreshFn, hide).catch(e => {
    message.error(e.message)
  })
}

function Index ({ visible, data, hide, refreshFn }) {
  const formRef = useRef(null)
  const [title, setTitle] = useState('')
  const [fileList, setFileList] = useState([])
  useEffect(() => {
    const c = formRef.current
    if (data !== null) {
      setTitle(`修改-${data.subtype}`)
      if (c !== null && data.pdf_file && data.pdf_file.length > 0) {
        const l = data.pdf_file.map(li => {
          li.name = li.original_filename
          return li
        })
        setFileList(l)
        c.setFieldsValue({
          file: {
            file: l[0],
            fileList: l
          }
        })
      }
    }
  }, [data])
  useEffect(() => {
    const c = formRef.current
    if (!visible && c !== null) {
      setFileList([])
      c.resetFields()
    }
  }, [visible])
  return (
    <Modal title={title} open={visible} onCancel={hide} onOk={() => formRef.current.submit()}>
      <Form ref={formRef} labelCol={{ flex: '88px' }} onFinish={(d) => submitHandle(data.id, d, refreshFn, hide)}>
        <Item label='文件' name='file' required={[{ require: true, message: '文件不能为空' }]}>
          <Upload {...getUploadPropsFn.call(this, formRef, '.pdf', fileList, v => setFileList(v))}>
            <Button disabled={fileList.length > 0}>
              <UploadOutlined /> 上传文件
            </Button>
            <span className={style['upload-placeholder']} onClick={e => e.stopPropagation()}>支持扩展名：.pdf</span>
          </Upload>
        </Item>
      </Form>
    </Modal>
  )
}

export default Index
